import {reqGetCode,reqUserLogin,reqUserRegister,reqUserInfo,reqLogout} from '@/api'

// 登录注册
const state = {
    code:'',
    token:localStorage.getItem('TOKEN') ,
    userInfo:{}
}
const mutations = {
    GETCODE(state,code){
        state.code = code
    },
    USERLOGIN(state,token){
        state.token =token
    },
    GETUSERINFO(state,userInfo){
        state.userInfo = userInfo
    },
    // 清除本地数据
    CLEAR(state){
        // 清除仓库数据和本地数据
        state.token=''
        state.userInfo={}
        localStorage.removeItem('TOKEN')
    }
}
const actions = {
    // 获取验证码
    async getCode({commit},phone){
        // 获取验证码的这个接口：正常发送到手机，
        const result = await reqGetCode(phone)
        if(result.code == 200){
            commit('GETCODE',result.data)
            return 'ok'
        }else{
            return Promise.reject(new Error('faile'))
        }
    },
    // 用户注册
    async userRegister({commit},user){
        const res =  await reqUserRegister(user)
        if(res.code==200){
            return 'ok'
        }else{
            return Promise.reject(new Error(res.message))
        }
    },
    // 用户登录
    async userLogin({commit},data){
        const res = await reqUserLogin(data)
        // 服务器下发的token，用户的唯一标识(uuid)
        // 将来经常通过token找服务器要用户信息
        if(res.code==200){
            commit('USERLOGIN',res.data.token)
            // 本地持久化存储token
            localStorage.setItem('TOKEN',res.data.token)
            return 'ok'
        }else{
            return Promise.reject(new Error('faile'))
        }
    },
    // 获取用户信息
    async getUserInfo({commit}){
        const res = await reqUserInfo()
        if(res.code==200){
            commit('GETUSERINFO',res.data)
            return 'ok'
        }else{
            return Promise.reject(new Error('faile'))
        }
    },
    // 退出登录
    async userLogout({commit}){
        // 通知服务器清除数据
        const res = await reqLogout()
        if(res.code == 200){
            commit('CLEAR')
            return 'ok'
        }else{
            Promise.reject(new Error('faile'))
        }
    }
}
const getters ={}
export default{
    state,
    mutations,
    actions,
    getters
}